﻿using System;
using System.Linq;
using System.Text;
using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Newtonsoft.Json.Linq;
using System.Security.Cryptography;
using KingdeeWebServiceProject.Data;
using KingdeeWebServiceProject.Utils;
using System.Data;
using Kingdee.BOS.Orm.DataEntity;
using System.Text.RegularExpressions;
using Kingdee.BOS.WebApi.FormService;
using System.Collections.Generic;

namespace KingdeeWebServiceProject
{
    //公共服务类
    internal static class CommonService
    {
        //辅助资料类别
        public const string Sex = "8bcd487d7147412b832895578579089f";               //性别
        public const string CredType = "B5BF313F-6FCA-4E9B-BE5A-1C06332B3B82";      //证件类型
        public const string Nationality = "9ab4ddbb7941472690c407e4343e59d7";       //民族
        public const string Educattion = "67e75837258142b8b42dcaeb3190bfce";        //学历
        public const string BusArea = "005056c00008968111e3b1a485b25282";           //商圈
        public const string Community = "005056c00008968111e3b1a550db9c1a";         //社区花园
        public const string Source = "bf6c06b51cc4a13a11e484d345759d8e";            //会员来源

        //地区信息
        public const string Country = "005056944621b40511e3ae740dbf1f1a";       //国家
        public const string Region = "005056944621b40511e3ae741eea45e3";        //省份
        public const string City = "005056944621b40511e3ae743f4229a2";          //城市
        public const string County = "005056944621b40511e3ae7448573af3";        //县区

        public const string SignKey = "SZJX@2016$2188KD";   //数据签名KEY


        public static string CreateUser = "{\"NeedUpDateFields\":[],\"NeedReturnFields\":[],\"IsDeleteEntry\":\"true\",\"SubSystemId\":\"\",\"IsVerifyBaseDataField\":\"false\",\"IsEntryBatchFill\":\"true\",\"ValidateFlag\":\"true\",\"NumberSearch\":\"true\",\"IsAutoAdjustField\":\"false\",\"InterationFlags\":\"\",\"IgnoreInterationFlag\":\"\",\"IsControlPrecision\":\"false\",\"ValidateRepeatJson\":\"false\",\"Model\":{\"FUserID\":0,\"FUserAccount\":\"用户账号\",\"FName\":\"用户名称\",\"FPRIMARYGROUP\":{\"FNumber\":\"003\"},\"FPhone\":\"电话\",\"FOrgInfo\":[{\"FOrgOrgId\":{\"FNumber\":\"100\"},\"FRoleInfo\":[{\"FRoleId\":{\"FNumber\":\"BID 000\"}}]},{\"FOrgOrgId\":{\"FNumber\":\"102\"},\"FRoleInfo\":[{\"FRoleId\":{\"FNumber\":\"BID 000\"}}]},{\"FOrgOrgId\":{\"FNumber\":\"103\"},\"FRoleInfo\":[{\"FRoleId\":{\"FNumber\":\"BID 000\"}}]},{\"FOrgOrgId\":{\"FNumber\":\"104\"},\"FRoleInfo\":[{\"FRoleId\":{\"FNumber\":\"BID 000\"}}]}]}}";

        public static string CreateCommonContact = "{\"NeedUpDateFields\":[],\"NeedReturnFields\":[],\"IsDeleteEntry\":\"true\",\"SubSystemId\":\"\",\"IsVerifyBaseDataField\":\"false\",\"IsEntryBatchFill\":\"true\",\"ValidateFlag\":\"true\",\"NumberSearch\":\"true\",\"IsAutoAdjustField\":\"false\",\"InterationFlags\":\"\",\"IgnoreInterationFlag\":\"\",\"IsControlPrecision\":\"false\",\"ValidateRepeatJson\":\"false\",\"Model\":{\"FCONTACTID\":0,\"FName\":\"用户名称\",\"FCompanyType\":\"BD_Customer\",\"FMobile\":\"电话\"}}";

        public static string CreateCustomer = "{\"NeedUpDateFields\":[],\"NeedReturnFields\":[],\"IsDeleteEntry\":\"true\",\"SubSystemId\":\"\",\"IsVerifyBaseDataField\":\"false\",\"IsEntryBatchFill\":\"true\",\"ValidateFlag\":\"true\",\"NumberSearch\":\"true\",\"IsAutoAdjustField\":\"false\",\"InterationFlags\":\"\",\"IgnoreInterationFlag\":\"\",\"IsControlPrecision\":\"false\",\"ValidateRepeatJson\":\"false\",\"Model\":{\"FCUSTID\":0,\"FCreateOrgId\":{\"FNumber\":\"区域\"},\"FUseOrgId\":{\"FNumber\":\"区域\"},\"FName\":\"名称\",\"FCOUNTRY\":{\"FNumber\":\"China\"},\"FIsGroup\":false,\"FIsDefPayer\":false,\"FCustTypeId\":{\"FNumber\":\"KHLB001_SYS\"},\"FTRADINGCURRID\":{\"FNumber\":\"PRE002\"},\"FTRANSLEADTIME\":0,\"FInvoiceType\":\"1\",\"FTaxType\":{\"FNumber\":\"SFL02_SYS\"},\"FPriority\":1,\"FTaxRate\":{\"FNumber\":\"SL02_SYS\"},\"FISCREDITCHECK\":true,\"FIsTrade\":true,\"FUncheckExpectQty\":false,\"F_QUDE_StoreFile\":{\"FNUMBER\":\"\"},\"F_QUDE_Saler\":{\"FNUMBER\":\"销售员\"},\"FT_BD_CUSTOMEREXT\":{\"FEnableSL\":false,\"FMarginLevel\":0.0,\"FALLOWJOINZHJ\":false},\"FT_BD_CUSTLOCATION\":[{\"FContactId\":{\"FNUMBER\":\"联系人编码\"},\"FIsDefaultConsigneeCT\":true,\"FIsCopy\":false}]}}";

        public static string CreateStoresfiles = "{\"NeedUpDateFields\":[],\"NeedReturnFields\":[],\"IsDeleteEntry\":\"true\",\"SubSystemId\":\"\",\"IsVerifyBaseDataField\":\"false\",\"IsEntryBatchFill\":\"true\",\"ValidateFlag\":\"true\",\"NumberSearch\":\"true\",\"IsAutoAdjustField\":\"false\",\"InterationFlags\":\"\",\"IgnoreInterationFlag\":\"\",\"IsControlPrecision\":\"false\",\"ValidateRepeatJson\":\"false\",\"Model\":{\"FID\":0,\"FCreateOrgId\":{\"FNumber\":\"区域\"},\"FUseOrgId\":{\"FNumber\":\"区域\"},\"FName\":\"商家名称\",\"FCustomerId\":{\"FNUMBER\":\"客户\"},\"F_QUDE_Supplier\":{\"FNUMBER\":\"销售员\"},\"F_QUDE_StoreEntity\":[{\"F_QUDE_StoreFile\":{\"FUSERACCOUNT\":\"用户账号\"},\"F_QUDE_OrgId\":{\"FNumber\":\"区域\"}}]}}";

        public static string saleAllStr = "{" +
                    "    \"NeedUpDateFields\": [],\n" +
                    "    \"NeedReturnFields\": [],\n" +
                    "    \"IsDeleteEntry\": \"true\",\n" +
                    "    \"SubSystemId\": \"\",\n" +
                    "    \"IsVerifyBaseDataField\": \"false\",\n" +
                    "    \"IsEntryBatchFill\": \"true\",\n" +
                    "    \"ValidateFlag\": \"true\",\n" +
                    "    \"NumberSearch\": \"true\",\n" +
                    "    \"InterationFlags\": \"\",\n" +
                    "    \"Model\": {\n" +
                    "        \"FID\": 主键,\n" +
                    "        \"FTransactions\": \"交易状态\",\n" +
                    "        \"FEndDate\": \"结束日期\",\n" +
                    "        \"FSaleQty\": 销售瓶数,\n" +
                    "        \"FALLAmount\": 总金额,\n" +
                    "        \"FEntity\": [\n" +
                    "            {\n" +
                    "                \"FEntryID\": 分录,\n" +
                    "                \"FBottlesSold\": 销售瓶数,\n" +
                    "                \"FSellingPrice\": 销售价格,\n" +
                    "                \"FActualPrice\": 实际销售价,\n" +
                    "                \"FTotalAmount\": 总金额\n" +
                    "            }\n" +
                    "        ]\n" +
                    "    }\n" +
                    "}";
        public static string purchaseAllStr = "{" +
                   "    \"NeedUpDateFields\": [],\n" +
                   "    \"NeedReturnFields\": [],\n" +
                   "    \"IsDeleteEntry\": \"true\",\n" +
                   "    \"SubSystemId\": \"\",\n" +
                   "    \"IsVerifyBaseDataField\": \"false\",\n" +
                   "    \"IsEntryBatchFill\": \"true\",\n" +
                   "    \"ValidateFlag\": \"true\",\n" +
                   "    \"NumberSearch\": \"true\",\n" +
                   "    \"InterationFlags\": \"\",\n" +
                   "    \"Model\": {\n" +
                   "        \"FID\": 主键,\n" +
                   "        \"FTransactions\": \"交易状态\",\n" +
                   "        \"FEndDate\": \"结束日期\",\n" +
                   "        \"FPurchaseQty\": 采购瓶数,\n" +
                   "        \"FALLAmount\": 总金额,\n" +
                   "        \"FEntity\": [\n" +
                   "            {\n" +
                   "                \"FEntryID\": 分录,\n" +
                   "                \"FPurchaseSold\": 采购瓶数,\n" +
                   "                \"FPurchasePrice\": 采购价格,\n" +
                   "                \"FPurchaseCost\": 采购成本,\n" +
                   "                \"FTotalAmount\": 总金额\n" +
                   "            }\n" +
                   "        ]\n" +
                   "    }\n" +
                   "}";
        #region saleStr
        public static string saleStr = "{" +
                    "    \"NeedUpDateFields\": [],\n" +
                    "    \"NeedReturnFields\": [],\n" +
                    "    \"IsDeleteEntry\": \"true\",\n" +
                    "    \"SubSystemId\": \"\",\n" +
                    "    \"IsVerifyBaseDataField\": \"true\",\n" +
                    "    \"IsEntryBatchFill\": \"true\",\n" +
                    "    \"ValidateFlag\": \"true\",\n" +
                    "    \"NumberSearch\": \"true\",\n" +
                    "    \"InterationFlags\": \"\",\n" +
                    "    \"Model\": {\n" +
                    "        \"FID\": 0,\n" +
                    "        \"FApplicationDate\": \"发布日期\",\n" +
                    "        \"FApplicationOrgId\": {\n" +
                    "            \"FNumber\": \"发布区域\"\n" +
                    "        },\n" +
                    "        \"FBCurrencyId\": {\n" +
                    "            \"FNumber\": \"结算币别\"\n" +
                    "        },\n" +
                    "        \"F_QUDE_Merchant\": {\n" +
                    "            \"FNUMBER\": \"商家信息\"\n" +
                    "        },\n" +
                    "        \"F_QUDE_Stock\": {\n" +
                    "            \"FNUMBER\": \"出货仓库\"\n" +
                    "        },\n" +
                    "        \"FBeginDate\": \"开始日期\",\n" +
                    "        \"FEndDate\": \"结束日期\",\n" +
                    "        \"FTransactions\": \"1\",\n" +
                    "        \"FSaleQty\": 销售瓶数,\n" +
                    "        \"FALLAmount\": 总金额,\n" +
                    "        \"FEntity\": [\n" +
                    "            {\n" +
                    "                \"FWineCode\": {\n" +
                    "                    \"FNUMBER\": \"酒款编码\"\n" +
                    "                },\n" +
                    "                \"FBottlesSold\": 销售瓶数,\n" +
                    "                \"FSellingPrice\": 销售价格,\n" +
                    "                \"FActualPrice\": 实际销售价,\n" +
                    "                \"FServiceRate\": 服务费率,\n" +
                    "                \"FTotalAmount\": 总金额\n" +
                    "            }\n" +
                    "        ]\n" +
                    "    }\n" +
                    "}";
        #endregion

        #region purchaseStr
        public static string purchaseStr = "{" +
                    "    \"NeedUpDateFields\": [],\n" +
                    "    \"NeedReturnFields\": [],\n" +
                    "    \"IsDeleteEntry\": \"true\",\n" +
                    "    \"SubSystemId\": \"\",\n" +
                    "    \"IsVerifyBaseDataField\": \"true\",\n" +
                    "    \"IsEntryBatchFill\": \"true\",\n" +
                    "    \"ValidateFlag\": \"true\",\n" +
                    "    \"NumberSearch\": \"true\",\n" +
                    "    \"InterationFlags\": \"\",\n" +
                    "    \"Model\": {\n" +
                    "        \"FID\": 0,\n" +
                    "        \"FApplicationDate\": \"发布日期\",\n" +
                    "        \"FApplicationOrgId\": {\n" +
                    "            \"FNumber\": \"发布区域\"\n" +
                    "        },\n" +
                    "        \"FBCurrencyId\": {\n" +
                    "            \"FNumber\": \"结算币别\"\n" +
                    "        },\n" +
                    "        \"F_QUDE_Merchant\": {\n" +
                    "            \"FNUMBER\": \"商家信息\"\n" +
                    "        },\n" +
                    "        \"F_QUDE_Stock\": {\n" +
                    "            \"FNUMBER\": \"出货仓库\"\n" +
                    "        },\n" +
                    "        \"FBeginDate\": \"开始日期\",\n" +
                    "        \"FEndDate\": \"结束日期\",\n" +
                    "        \"FTransactions\": \"1\",\n" +
                    "        \"FPurchaseQty\": 采购瓶数,\n" +
                    "        \"FALLAmount\": 总金额,\n" +
                    "        \"FEntity\": [\n" +
                    "            {\n" +
                    "                \"FWineCode\": {\n" +
                    "                    \"FNUMBER\": \"酒款编码\"\n" +
                    "                },\n" +
                    "                \"FPurchaseSold\": 采购瓶数,\n" +
                    "                \"FPurchasePrice\": 采购价格,\n" +
                    "                \"FPurchaseCost\": 采购成本,\n" +
                    "                \"FServiceRate\": 服务费率,\n" +
                    "                \"FTotalAmount\": 总金额\n" +
                    "            }\n" +
                    "        ]\n" +
                    "    }\n" +
                    "}";
        #endregion



        internal static JObject SaveMethod(Context context, string FormId, string jsonData)
        {
            JObject result = new JObject
            {
                { "code", 500 }
            };
            try
            {
                StringBuilder stringBuilder = new StringBuilder();//接收失败原因
                object saveResult = WebApiServiceCall.Save(context, FormId, jsonData);//调用保存方法  
                Dictionary<string, object> responseStatus = ((Dictionary<string, object>)((Dictionary<string, object>)saveResult)["Result"])["ResponseStatus"] as Dictionary<String, object>;
                JObject obj = JObject.FromObject(saveResult);
                JObject resultStr = JObject.Parse(obj["Result"].ToString());
                JObject ResponseStatus = JObject.Parse(resultStr["ResponseStatus"].ToString());
                if (ResponseStatus["IsSuccess"].ToString().ToUpper() == "TRUE")
                {
                    if (!ResponseStatus["SuccessEntitys"].ToString().Equals("[]"))
                    {
                        result["code"] = 200;
                        JArray content = JArray.Parse(ResponseStatus["SuccessEntitys"].ToString());
                        result["Number"] = content.First["Number"].ToString();
                    }
                    else
                    {
                        result.Add("msg", "保存失败！详情：未知错误");
                    }
                }
                else
                {
                    List<object> errors = responseStatus["Errors"] as List<object>;
                    for (int a = 0; a < errors.Count(); a++)
                    {
                        Dictionary<string, object> keyValues = errors[a] as Dictionary<string, object>;
                        stringBuilder.AppendLine("第" + keyValues["DIndex"] + "行分录:" + keyValues["Message"]);
                    }
                    result.Add("msg", "保存失败！详情：" + stringBuilder.ToString());
                }
            }
            catch (Exception ex)
            {
                result.Add("msg", "保存失败！详情：" + ex.Message);
            }
            return result;
        }

        internal static JObject SubmitMethod(Context context, string FormId, string jsonData)
        {
            JObject result = new JObject
            {
                { "code", 500 }
            };
            try
            {
                StringBuilder stringBuilder = new StringBuilder();//接收失败原因
                object submitResult = WebApiServiceCall.Submit(context, FormId, jsonData);//调用保存方法  
                Dictionary<string, object> responseStatus = ((Dictionary<string, object>)((Dictionary<string, object>)submitResult)["Result"])["ResponseStatus"] as Dictionary<String, object>;

                JObject obj = JObject.FromObject(submitResult);
                JObject resultStr = JObject.Parse(obj["Result"].ToString());
                JObject ResponseStatus = JObject.Parse(resultStr["ResponseStatus"].ToString());
                if (ResponseStatus["IsSuccess"].ToString().ToUpper() == "TRUE")
                {
                    result["code"] = 200;
                }
                else
                {
                    List<object> errors = responseStatus["Errors"] as List<object>;
                    for (int a = 0; a < errors.Count(); a++)
                    {
                        Dictionary<string, object> keyValues = errors[a] as Dictionary<string, object>;
                        stringBuilder.AppendLine("第" + keyValues["DIndex"] + "行分录:" + keyValues["Message"]);
                    }
                    result.Add("msg", "提交失败！详情：" + stringBuilder.ToString());
                }
            }
            catch (Exception ex)
            {
                result.Add("msg", "提交失败！详情：" + ex.Message);
            }
            return result;
        }

        internal static JObject AuditMethod(Context context, string FormId, string jsonData)
        {
            JObject result = new JObject
            {
                { "code", 500 }
            };
            try
            {
                StringBuilder stringBuilder = new StringBuilder();//接收失败原因
                object auditResult = WebApiServiceCall.Audit(context, FormId, jsonData);//调用方法  
                Dictionary<string, object> responseStatus = ((Dictionary<string, object>)((Dictionary<string, object>)auditResult)["Result"])["ResponseStatus"] as Dictionary<String, object>;

                JObject obj = JObject.FromObject(auditResult);
                JObject resultStr = JObject.Parse(obj["Result"].ToString());
                JObject ResponseStatus = JObject.Parse(resultStr["ResponseStatus"].ToString());
                if (ResponseStatus["IsSuccess"].ToString().ToUpper() == "TRUE")
                {
                    result["code"] = 200;
                }
                else
                {
                    List<object> errors = responseStatus["Errors"] as List<object>;
                    for (int a = 0; a < errors.Count(); a++)
                    {
                        Dictionary<string, object> keyValues = errors[a] as Dictionary<string, object>;
                        stringBuilder.AppendLine("第" + keyValues["DIndex"] + "行分录:" + keyValues["Message"]);
                    }
                    result.Add("msg", "审核失败！详情：" + stringBuilder.ToString());
                }
            }
            catch (Exception ex)
            {
                result.Add("msg", "审核失败！详情：" + ex.Message);
            }
            return result;
        }

        internal static JObject UnAuditMethod(Context context, string FormId, string jsonData)
        {
            JObject result = new JObject
            {
                { "code", 500 }
            };
            try
            {
                StringBuilder stringBuilder = new StringBuilder();//接收失败原因
                object auditResult = WebApiServiceCall.UnAudit(context, FormId, jsonData);//调用方法  
                Dictionary<string, object> responseStatus = ((Dictionary<string, object>)((Dictionary<string, object>)auditResult)["Result"])["ResponseStatus"] as Dictionary<String, object>;

                JObject obj = JObject.FromObject(auditResult);
                JObject resultStr = JObject.Parse(obj["Result"].ToString());
                JObject ResponseStatus = JObject.Parse(resultStr["ResponseStatus"].ToString());
                if (ResponseStatus["IsSuccess"].ToString().ToUpper() == "TRUE")
                {
                    result["code"] = 200;
                }
                else
                {
                    List<object> errors = responseStatus["Errors"] as List<object>;
                    for (int a = 0; a < errors.Count(); a++)
                    {
                        Dictionary<string, object> keyValues = errors[a] as Dictionary<string, object>;
                        stringBuilder.AppendLine("第" + keyValues["DIndex"] + "行分录:" + keyValues["Message"]);
                    }
                    result.Add("msg", "反审核失败！详情：" + stringBuilder.ToString());
                }
            }
            catch (Exception ex)
            {
                result.Add("msg", "反审核失败！详情：" + ex.Message);
            }
            return result;
        }


        internal static JObject DeleteMethod(Context context, string FormId, string jsonData)
        {
            JObject result = new JObject
            {
                { "code", 500 }
            };
            try
            {
                StringBuilder stringBuilder = new StringBuilder();//接收失败原因
                object auditResult = WebApiServiceCall.Delete(context, FormId, jsonData);//调用方法  
                Dictionary<string, object> responseStatus = ((Dictionary<string, object>)((Dictionary<string, object>)auditResult)["Result"])["ResponseStatus"] as Dictionary<String, object>;

                JObject obj = JObject.FromObject(auditResult);
                JObject resultStr = JObject.Parse(obj["Result"].ToString());
                JObject ResponseStatus = JObject.Parse(resultStr["ResponseStatus"].ToString());
                if (ResponseStatus["IsSuccess"].ToString().ToUpper() == "TRUE")
                {
                    result["code"] = 200;
                }
                else
                {
                    List<object> errors = responseStatus["Errors"] as List<object>;
                    for (int a = 0; a < errors.Count(); a++)
                    {
                        Dictionary<string, object> keyValues = errors[a] as Dictionary<string, object>;
                        stringBuilder.AppendLine("第" + keyValues["DIndex"] + "行分录:" + keyValues["Message"]);
                    }
                    result.Add("msg", "删除失败！详情：" + stringBuilder.ToString());
                }
            }
            catch (Exception ex)
            {
                result.Add("msg", "删除失败！详情：" + ex.Message);
            }
            return result;
        }


        internal static JObject CancelAssign(Context context, string FormId, string jsonData)
        {
            JObject result = new JObject
            {
                { "code", 500 }
            };
            try
            {
                StringBuilder stringBuilder = new StringBuilder();//接收失败原因
                object auditResult = WebApiServiceCall.CancelAssign(context, FormId, jsonData);//调用方法  
                Dictionary<string, object> responseStatus = ((Dictionary<string, object>)((Dictionary<string, object>)auditResult)["Result"])["ResponseStatus"] as Dictionary<String, object>;

                JObject obj = JObject.FromObject(auditResult);
                JObject resultStr = JObject.Parse(obj["Result"].ToString());
                JObject ResponseStatus = JObject.Parse(resultStr["ResponseStatus"].ToString());
                if (ResponseStatus["IsSuccess"].ToString().ToUpper() == "TRUE")
                {
                    result["code"] = 200;
                }
                else
                {
                    List<object> errors = responseStatus["Errors"] as List<object>;
                    for (int a = 0; a < errors.Count(); a++)
                    {
                        Dictionary<string, object> keyValues = errors[a] as Dictionary<string, object>;
                        stringBuilder.AppendLine("第" + keyValues["DIndex"] + "行分录:" + keyValues["Message"]);
                    }
                    result.Add("msg", "撤销失败！详情：" + stringBuilder.ToString());
                }
            }
            catch (Exception ex)
            {
                result.Add("msg", "撤销失败！详情：" + ex.Message);
            }
            return result;
        }

        //登录系统验证方法
        internal static bool LoginSystemAuth(JObject jParams, JObject result, out Context ctx)
        {
            ctx = null;
            result["Result"] = false;

            string dataCenterID = GetJParamString(jParams, "dataCenterID");
            if (string.IsNullOrWhiteSpace(dataCenterID))
            {
                result["Message"] = "参数【dataCenterID：数据中心】不能为空！";
                return false;
            }

            string userName = GetJParamString(jParams, "userName");
            userName = "肖浩";
            if (string.IsNullOrWhiteSpace(userName))
            {
                result["Message"] = "参数【userName：登陆用户】不能为空！";
                return false;
            }

            string passWord = GetJParamString(jParams, "passWord");
            passWord = "kingdee@123";
            string userToken = GetJParamString(jParams, "userToken");

            bool isEncrypt = false;
            string strEncrypt = CommonService.GetJParamString(jParams, "isEncrypt");
            bool.TryParse(strEncrypt, out isEncrypt);
            if (isEncrypt)
            {
                dataCenterID = RSACryptoService.Decrypt(dataCenterID, RSACryptoService.privateKey);
                userName = RSACryptoService.Decrypt(userName, RSACryptoService.privateKey);
                passWord = RSACryptoService.Decrypt(passWord, RSACryptoService.privateKey);
                userToken = RSACryptoService.Decrypt(userToken, RSACryptoService.privateKey);
            }

            JObject logResult = null;

            try
            {
                LogDataCenterForWebService logService = new LogDataCenterForWebService();
                logResult = logService.Auth(dataCenterID, userName, passWord, userToken, out ctx);
            }
            catch (Exception ex)
            {
                result["Message"] = "本次登陆错误：" + ex;
                return false;
            }

            if (!Convert.ToBoolean((logResult["Result"] as JValue).Value))
            {
                result["Message"] = "本次登陆错误：" + logResult["Message"];
                return false;
            }
            if (ctx == null)
            {
                result["Message"] = "WebService登录失败，登录上下文为空，请确认登录信息是否正确";
                return false;
            }
            string TimeStamp = Convert.ToString(DateTime.Now.AddHours(2).ToString("yyyy-MM-dd HH:mm:ss"));
            result["TimeStamp"] = TimeStamp;
            result["UserToken"] = logResult["UserToken"];
            result["Result"] = logResult["Result"];
            return true;
        }

        //密码混淆
        private static string EcryptPassWord(string passWord)
        {
            string strPassWord = "";
            if (!string.IsNullOrWhiteSpace(passWord))
            {
                char[] charPassWord = passWord.ToCharArray();
                for (int i = 0; i < charPassWord.Length; i++)
                {
                    strPassWord += charPassWord[i].ToString();
                    strPassWord += charPassWord[charPassWord.Length - i - 1].ToString();
                }
            }

            return strPassWord;
        }

        //密码解密
        private static string DecryptPassWord(string passWord)
        {
            string strPassWord = "";
            if (!string.IsNullOrWhiteSpace(passWord))
            {
                char[] charPassWord = passWord.ToCharArray();
                for (int i = 0; i < charPassWord.Length; i++)
                {
                    if (i % 2 == 0)
                    {
                        strPassWord += charPassWord[i].ToString();
                    }
                }
            }

            return strPassWord;
        }

        //获取JSon参数值(字符串）
        internal static string GetJParamString(JObject jParams, string jKey)
        {
            JToken jValue = null;

            if (!jParams.TryGetValue(jKey, out jValue) || jValue == null || string.IsNullOrWhiteSpace(jValue.ToString()))
            {
                return "";
            }

            return jValue.ToString();
        }

        //获取JSon参数值(JObject）
        internal static JObject GetJParamObject(JObject jParams, string jKey)
        {
            JToken jValue = null;

            if (!jParams.TryGetValue(jKey, out jValue) || jValue == null || string.IsNullOrWhiteSpace(jValue.ToString()))
            {
                return null;
            }

            return JObject.FromObject(jValue);
        }

        //获取JSon参数值(JArray）
        internal static JArray GetJParamArray(JObject jParams, string jKey)
        {
            JToken jValue = null;

            if (!jParams.TryGetValue(jKey, out jValue) || jValue == null || string.IsNullOrWhiteSpace(jValue.ToString()))
            {
                return null;
            }

            return JArray.FromObject(jValue);
        }

        //获取策略控制下分配组组织内码
        internal static string orgIDList(Context ctx, string FCreateOrgNumber)
        {
            string orgList = "";
            string strSql = string.Format(@"select t2.FTARGETORGID from T_ORG_BDCtrlPolicy t1
                                            inner join T_ORG_BDCtrlTOrgEntry t2 on t1.FPOLICYID = t2.FPOLICYID 
                                            inner join T_ORG_ORGANIZATIONS t3 on t1.FCREATEORGID = t3.FORGID
                                            where t3.FNUMBER = '{0}' and t1.FBASEDATATYPEID = 'BD_MATERIAL'", FCreateOrgNumber);
            var Datas = DBUtils.ExecuteDynamicObject(ctx, strSql);
            if (Datas != null && Datas.Count > 0)
            {
                foreach (var data in Datas)
                {
                    orgList = orgList + data["ID"].ToString() + ",";
                }
                orgList.Remove(orgList.Length - 1, 1);
            }
            return orgList;
        }

        //获取礼券ID（通过编码）
        internal static long GetTicketID(Context ctx, string ticketNumber)
        {
            if (string.IsNullOrWhiteSpace(ticketNumber))
            {
                return 0;
            }

            string strSql = string.Format("select top 1 t1.FID as Id  from CMK_RT_TicketsInfo t1 where t1.FTICKETNO = '{0}' ", ticketNumber);
            var Datas = DBUtils.ExecuteDynamicObject(ctx, strSql);
            if (Datas != null && Datas.Count > 0)
            {
                return Convert.ToInt64(Datas.First()["Id"]);
            }
            return 0;
        }

        //获取基础资料ID（通过编码或者名称）
        internal static long GetBaseDataIdByValue(Context ctx, string strTable, string strId, string strKey, string strValue, long useOrgId = 0)
        {
            if (string.IsNullOrWhiteSpace(strValue))
            {
                return 0;
            }

            string strSql = string.Format("SELECT TOP 1 {1} AS Id FROM {0} WHERE {2} = '{3}' ", strTable, strId, strKey, strValue);
            if (useOrgId > 0)
            {
                strSql = string.Format("{0} AND FUseOrgId = {1} ", strSql, useOrgId);
            }

            //通过上下文获取
            var Datas = DBUtils.ExecuteDynamicObject(ctx, strSql);
            if (Datas != null && Datas.Count > 0)
            {
                return Convert.ToInt64(Datas.First()["Id"]);
            }
            //通过直连数据库获取
            //var ds = Data.XDDDBUtils.ExecuteDateSet(strSql); //DBUtils.ExecuteDataSet(strSql);
            //if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            //{
            //    return ds.Tables[0].Rows[0]["id"].ToInt64();
            //}
            return 0;
        }

        //获取基础资料ID（通过编码或者名称）
        internal static String VKGetBaseDataIdByValue(Context ctx, string OrgNumber)
        {
            if (string.IsNullOrWhiteSpace(OrgNumber))
            {
                return "0";
            }

            string strSql = string.Format(@"select  TOP 1  T1.FNUMBER AS FNUMBER from ora_VK_OrgidMappingTable T
                                            INNER JOIN T_ORG_ORGANIZATIONS T1 ON T1.FORGID = T.FORGID
                                            WHERE T.FVKACCOUNTNO = '{0}' ", OrgNumber);
            //通过上下文获取
            var Datas = DBUtils.ExecuteDynamicObject(ctx, strSql);
            if (Datas != null && Datas.Count > 0)
            {
                return Convert.ToString(Datas.First()["FNUMBER"]);
            }
            return "0";
        }
        //获取银行账号（通过编码或者名称）
        internal static String VKBANKACNTByValue(Context ctx, string PAYORGID)
        {
            if (string.IsNullOrWhiteSpace(PAYORGID))
            {
                return "0";
            }

            string strSql = string.Format(@"select t.FNUMBER as FNUMBER  from T_CN_BANKACNT t
                                            inner join  T_ORG_ORGANIZATIONS t1 on t1.FORGID = t.FCREATEORGID 
                                            where FISDEFAULTBANK = '1' and t1.FNUMBER = '{0}'", PAYORGID);
            //通过上下文获取
            var Datas = DBUtils.ExecuteDynamicObject(ctx, strSql);
            if (Datas != null && Datas.Count > 0)
            {
                return Convert.ToString(Datas.First()["FNUMBER"]);
            }
            return "0";
        }
        //物料
        internal static String VKFMaterialId(Context ctx, string FMaterialId)
        {
            if (string.IsNullOrWhiteSpace(FMaterialId))
            {
                return "0";
            }

            string strSql = string.Format(@"SELECT TOP 1 FNUMBER  FROM T_BD_MATERIAL WHERE FTHIRDBILLNO = '{0}'", FMaterialId);
            //通过上下文获取
            var Datas = DBUtils.ExecuteDynamicObject(ctx, strSql);
            if (Datas != null && Datas.Count > 0)
            {
                return Convert.ToString(Datas.First()["FNUMBER"]);
            }
            return "0";
        }
        //仓库
        internal static String VKFStockId(Context ctx, string FStockId)
        {
            if (string.IsNullOrWhiteSpace(FStockId))
            {
                return "0";
            }

            string strSql = string.Format(@"SELECT TOP 1 FNUMBER  FROM T_BD_STOCK WHERE FTHIRDBILLNO = '{0}'", FStockId);
            //通过上下文获取
            var Datas = DBUtils.ExecuteDynamicObject(ctx, strSql);
            if (Datas != null && Datas.Count > 0)
            {
                return Convert.ToString(Datas.First()["FNUMBER"]);
            }
            return "0";
        }
        //供应商
        internal static String VKFSupplierId(Context ctx, string FSupplierId)
        {
            if (string.IsNullOrWhiteSpace(FSupplierId))
            {
                return "0";
            }

            string strSql = string.Format(@"SELECT TOP 1 FNUMBER  FROM T_BD_SUPPLIER WHERE FTHIRDBILLNO = '{0}'", FSupplierId);
            //通过上下文获取
            var Datas = DBUtils.ExecuteDynamicObject(ctx, strSql);
            if (Datas != null && Datas.Count > 0)
            {
                return Convert.ToString(Datas.First()["FNUMBER"]);
            }
            return "0";
        }

        //客户
        internal static String VKFCustomerID(Context ctx, string FCustomerID)
        {
            if (string.IsNullOrWhiteSpace(FCustomerID))
            {
                return "0";
            }

            string strSql = string.Format(@"SELECT TOP 1 FNUMBER  from T_BD_CUSTOMER WHERE FTHIRDBILLNO = '{0}'", FCustomerID);
            //通过上下文获取
            var Datas = DBUtils.ExecuteDynamicObject(ctx, strSql);
            if (Datas != null && Datas.Count > 0)
            {
                return Convert.ToString(Datas.First()["FNUMBER"]);
            }
            return "0";
        }

        //获取辅助资料ID（通过编码或者名称）
        internal static string GetAuxDataIdByName(Context ctx, string strValue, string strType)
        {
            if (string.IsNullOrWhiteSpace(strValue))
            {
                return "";
            }

            string strSql = string.Format(@"SELECT TOP 1 t1.FEntryId FROM T_BAS_ASSISTANTDATAENTRY t1 INNER JOIN T_BAS_ASSISTANTDATAENTRY_L t2 ON t1.FEntryId = t2.FEntryId AND t2.FLOCALEID = 2052 
                WHERE t1.FID = '{0}' AND (t1.FNumber = '{1}' OR t2.FDataValue = '{1}') ", strType, strValue);
            var Datas = DBUtils.ExecuteDynamicObject(ctx, strSql);
            if (Datas != null && Datas.Count > 0)
            {
                return Convert.ToString(Datas.First()["FEntryId"]);
            }

            return "";
        }

        internal static string xGetAuxDataIdByName(Context ctx, string strValue, string strType)
        {
            if (string.IsNullOrWhiteSpace(strValue))
            {
                return "";
            }

            string strSql = string.Format(@"SELECT TOP 1 t1.FEntryId FROM T_BAS_ASSISTANTDATAENTRY t1 INNER JOIN T_BAS_ASSISTANTDATAENTRY_L t2 ON t1.FEntryId = t2.FEntryId AND t2.FLOCALEID = 2052 
                WHERE t1.FID = '{0}' AND (t1.FNumber = '{1}' OR t2.FDataValue = '{1}') ", strType, strValue);
            DataSet Datas = XDDDBUtils.ExecuteDateSet(strSql);
            //var Datas = DBUtils.ExecuteDynamicObject(ctx, strSql);
            if (Datas != null && Datas.Tables.Count > 0)
            {
                return Convert.ToString(Datas.Tables[0].Rows[0]["FEntryId"]);
            }

            return "";
        }
        //获取地区信息ID（通过编码或者名称）
        internal static long GetAreaDetailIdByValue(Context ctx, string strValue, string strType)
        {
            if (string.IsNullOrWhiteSpace(strValue))
            {
                return 0;
            }

            string strSql = string.Format(@"SELECT TOP 1 t1.FDetailId FROM T_ECC_LOGISTICSAREADETAIL t1 INNER JOIN T_ECC_LOGISTICSAREADETAIL_L t2 ON t1.FDETAILID = t2.FDETAILID AND t2.FLOCALEID = 2052 
                WHERE t1.FTYPEID = '{0}' AND (t1.FNumber = '{1}' OR t2.FDataValue = '{1}') ", strType, strValue);
            var Datas = DBUtils.ExecuteDynamicObject(ctx, strSql);
            if (Datas != null && Datas.Count > 0)
            {
                return Convert.ToInt64(Datas.First()["FDetailId"]);
            }

            return 0;
        }

        //获取基础资料编码（通过id）
        internal static string GetBaseDataNumberByValue(Context ctx, string strTable, string strId, string strKey, long strValue, long useOrgId = 0)
        {
            if (strValue == 0)
            {
                return "";
            }

            string strSql = string.Format("SELECT TOP 1 {1} AS Id FROM {0} WHERE {2} = '{3}' ", strTable, strId, strKey, strValue);
            if (useOrgId > 0)
            {
                strSql = string.Format("{0} AND FUseOrgId = {1} ", strSql, useOrgId);
            }

            var Datas = DBUtils.ExecuteDynamicObject(ctx, strSql);
            if (Datas != null && Datas.Count > 0)
            {
                return Datas.First()["Id"].ToString();
            }

            return "";
        }

        //获取礼券对应状态（根据交易序列号）
        internal static string getTicketTransSerial(Context ctx, string ticketNo)
        {
            string strSql = string.Format(@"select t2.FTRANSSERIAL from CMK_RT_TicketsInfo t1
                                            inner join CMK_Ticket_ActionFlow t2 on t2.FTicketId = t1.fID where t1.FTICKETSTATUS = 'C' and t1.FTICKETNO = '{0}' and t2.FBIZTYPE = 'CMK_LS_Retail'", ticketNo);
            //var Datas = DBUtils.ExecuteDynamicObject(ctx, strSql);
            //if (Datas != null && Datas.Count > 0)
            //{
            //    return Datas.First()["FTRANSSERIAL"].ToString();
            //}
            //else
            //{
            //    return null;
            //}

            var ds = Data.XDDDBUtils.ExecuteDateSet(strSql);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                return ds.Tables[0].Rows[0]["FTRANSSERIAL"].ToString();
            }
            else
            {
                return null;
            }
        }

        //获取礼券对应状态
        internal static string getTicketStatus(Context ctx, string ticketNo)
        {
            string strSql = string.Format(@"select t1.FTICKETSTATUS from CMK_RT_TicketsInfo t1
                                             where t1.FTICKETNO = '{0}' ", ticketNo);
            //上下文获取
            //var Datas = DBUtils.ExecuteDynamicObject(ctx, strSql);
            //if (Datas != null && Datas.Count > 0)
            //{
            //    return Datas.First()["FTICKETSTATUS"].ToString();
            //}
            //直连获取
            var ds = Data.XDDDBUtils.ExecuteDateSet(strSql); //DBUtils.ExecuteDataSet(strSql);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                return ds.Tables[0].Rows[0]["FTICKETSTATUS"].ToString();
            }
            return "";
        }

        //获取时间戳
        internal static bool CompareTimeStamp(string TimeStamp, JObject result)
        {
            long lTimeStamp = 0;
            if (string.IsNullOrEmpty(TimeStamp))
            {
                result["Message"] = "参数【TimeStamp：时间戳】不能为空！";
                return false;
            }

            if (!long.TryParse(TimeStamp, out lTimeStamp))
            {
                result["Message"] = string.Format("参数【TimeStamp：时间戳 {0}】格式错误！", TimeStamp);
                return false;
            }

            //比较时间戳（10分钟）
            long curTimeStamp = Convert.ToInt64(DateTime.Now.AddMinutes(-10).ToString("yyyyMMddHHmmss"));
            if (curTimeStamp > lTimeStamp)
            {
                result["Message"] = "本次请求已经超时失效！";
                return false;
            }

            curTimeStamp = Convert.ToInt64(DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));
            if (curTimeStamp < lTimeStamp)
            {
                result["Message"] = "本次请求已经超时失效！";
                return false;
            }

            return true;
        }

        //生成SHA1序列化数字签名
        internal static string GetSign(string strKey)
        {
            StringBuilder sbSign = new StringBuilder();

            byte[] byteStr = Encoding.UTF8.GetBytes(strKey);

            byte[] byteSign = SHA1.Create().ComputeHash(byteStr);

            foreach (var b in byteSign)
            {
                sbSign.Append(b.ToString("x2"));
            }

            return sbSign.ToString();
        }

        //校验SHA1序列化数字签名
        internal static bool VerifySign(string strKey, string strSign)
        {
            string strNewSign = GetSign(strKey);

            return strSign.Equals(strNewSign);
        }


        //根据门店获取组织id
        internal static long GetStockIdByBranch(Context ctx, long lBranchId)
        {
            long num = 0L;
            DynamicObjectCollection source = DBUtils.ExecuteDynamicObject(ctx, string.Format("select top 1 t2.FSTOCKID as FSTOCKID from CMK_LS_Branch t1 inner join CMK_LS_BranchStock t2 on t1.FID = t2.FID WHERE t1.FID = {0} ", lBranchId), null, null, CommandType.Text, new SqlParam[0]);
            if ((source != null) && (source.Count > 0))
            {
                num = Convert.ToInt64(source.First<DynamicObject>()["FSTOCKID"]);
            }
            return num;
        }

        //获取物料对应税率
        internal static string GetTaxRateByMaterialId(Context ctx, long MaterialId)
        {
            string num = "0";
            DynamicObjectCollection source = DBUtils.ExecuteDynamicObject(ctx, string.Format(@"select t3.FTAXRATE from T_BD_MATERIAL t1
                    inner join t_BD_MaterialBase t2 on t1.FMATERIALID = t2.FMATERIALID
                    inner join T_BD_TAXRATE t3 on t2.FTAXRATEID = t3.FID WHERE t1.FMATERIALID = {0} ", MaterialId), null, null, CommandType.Text, new SqlParam[0]);
            if ((source != null) && (source.Count > 0))
            {
                num = Convert.ToString(source.First<DynamicObject>()["FTAXRATE"]);
            }
            return num;
        }

        //校验实体卡消费密码
        internal static bool CheckCardPassWord(string password, string cardno)
        {
            bool is_correct = false;
            string MDPassword = Sign(password);
            bool ISConsumByPWD = false;
            string K3Password = "";
            string sql = string.Format("select t1.FCONSUMEPASSWORD,t1.FConsumByPWD from CMK_T_VIP_CARD t1 where FNUMBER='{0}'", cardno);
            var ds = Data.XDDDBUtils.ExecuteDateSet(sql);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                K3Password = Convert.ToString(ds.Tables[0].Rows[0]["FCONSUMEPASSWORD"]);
                ISConsumByPWD = Convert.ToBoolean(ds.Tables[0].Rows[0]["FConsumByPWD"]);
                if (ISConsumByPWD)
                {
                    if (MDPassword.Equals(K3Password))
                    {
                        is_correct = true;
                    }
                    else
                    {
                        is_correct = false;
                    }
                }
                else
                {
                    is_correct = true;
                }
            }
            else
            {
                is_correct = false;
            }
            return is_correct;
        }

        //获取品牌辅助资料ID（通过编码）
        internal static string GetBrandIpByNumber(Context ctx, string Number)
        {
            if (string.IsNullOrWhiteSpace(Number))
            {
                return "";
            }

            string strSql = string.Format("select Top  1 B.FEntryId from T_BAS_ASSISTANTDATA A inner join T_BAS_ASSISTANTDATAENTRY B on B.FID=A.FID left join T_BAS_ASSISTANTDATAENTRY_L C on C.FENTRYID=B.FENTRYID where A.FNUMBER='BusinessMode' and B.FNUMBER='{0}'", Number);
            var Datas = DBUtils.ExecuteDynamicObject(ctx, strSql);
            if (Datas != null && Datas.Count > 0)
            {
                return Convert.ToString(Datas.First()["FEntryId"]);
            }

            return "";
        }

        //根据门店获取组织id
        internal static long GetOrgIdByBranch(Context ctx, long lBranchId)
        {
            long num = 0L;
            DynamicObjectCollection source = DBUtils.ExecuteDynamicObject(ctx, string.Format("SELECT TOP 1 FORGID FROM CMK_LS_Branch WHERE FID = {0} ", lBranchId), null, null, CommandType.Text, new SqlParam[0]);
            if ((source != null) && (source.Count > 0))
            {
                num = Convert.ToInt64(source.First<DynamicObject>()["FORGID"]);
            }
            return num;
        }

        //卡交易（根据交易序列号）
        internal static bool getTransSerial(Context ctx, string CardNo, string TransSerial)
        {
            string strSql = string.Format(@"  select FTRANSSERIAL from CMK_VIP_T_CardAction t
           inner join CMK_T_VIP_CARD t1 on t1.FCardID = t.FCARDID  where FTRANSSERIAL  = '{0}' and t1.FNUMBER = '{1}'", TransSerial, CardNo);

            var ds = XDDDBUtils.ExecuteDateSet(strSql);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        //加密方法(MD5)
        internal static string Sign(string json)
        {

            //将空格和特殊字符串去掉
            string Mdjson = Regex.Replace(json, @"\s", "");
            StringBuilder enValue = new StringBuilder();
            enValue.Append(Mdjson);
            // 使用MD5加密
            byte[] bytes = encryptMD5(enValue.ToString());
            // 把二进制转化为大写的十六进制
            return byte2hex(bytes);
        }

        private static byte[] encryptMD5(String data)
        {
            byte[] bytes = null;
            try
            {
                MD5 md5 = new MD5CryptoServiceProvider();
                bytes = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(data));

                //MessageDigest md = MessageDigest.getInstance("MD5");
                //bytes = md.digest(data.getBytes("UTF-8"));
            }
            catch (Exception)
            {

            }
            return bytes;
        }
        private static string byte2hex(byte[] bytes)
        {
            string md5Str = "0123456789ABCDEF";
            string sign = string.Empty;
            for (int i = 0; i < bytes.Length; i++)
            {
                int a = 0xf & bytes[i] >> 4;
                int b = bytes[i] & 0xf;
                sign += md5Str.Substring(0xf & bytes[i] >> 4, 1) + md5Str[bytes[i] & 0xf];
            }
            return sign.ToString();
        }

        #region  DataSet转换为Json
        /// <summary>    
        /// DataSet转换为Json   
        /// </summary>    
        /// <param name="dataSet">DataSet对象</param>   
        /// <returns>Json字符串</returns>    
        internal static string ToJson(DataSet dataSet)
        {

            string jsonString = "";
            foreach (DataTable table in dataSet.Tables)
            {
                if (table.Rows.Count > 1 && table.Rows.Count != 0L)
                {
                    jsonString += ToJson(table);
                }
                else
                {

                }
            }
            //jsonString = jsonString.TrimEnd(',');
            jsonString.Remove(jsonString.Length - 1, 1);

            return jsonString + "]";
        }
        #endregion

        #region Datatable转换为Json
        /// <summary>     
        /// Datatable转换为Json     
        /// </summary>    
        /// <param name="table">Datatable对象</param>     
        /// <returns>Json字符串</returns>     
        public static string ToJson(DataTable dt)
        {
            StringBuilder jsonString = new StringBuilder();
            //jsonString.Append("[");
            DataRowCollection drc = dt.Rows;
            for (int i = 0; i < drc.Count; i++)
            {
                jsonString.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string strKey = dt.Columns[j].ColumnName;
                    string strValue = drc[i][j].ToString();
                    Type type = dt.Columns[j].DataType;
                    jsonString.Append("\"" + strKey + "\":");
                    strValue = StringFormat(strValue, type);
                    if (j < dt.Columns.Count - 1)
                    {
                        jsonString.Append(strValue + ",");
                    }
                    else
                    {
                        jsonString.Append(strValue);
                    }
                }
                jsonString.Append("},");
            }
            //jsonString.Remove(jsonString.Length - 1, 1);
            //jsonString.Append("]");
            return jsonString.ToString();
        }
        /// <summary>    
        /// DataTable转换为Json     
        /// </summary>    
        public static string ToJson(DataTable dt, string jsonName)
        {
            StringBuilder Json = new StringBuilder();
            if (string.IsNullOrEmpty(jsonName))
                jsonName = dt.TableName;
            Json.Append("{\"" + jsonName + "\":[");
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Json.Append("{");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        Type type = dt.Rows[i][j].GetType();
                        Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + StringFormat(dt.Rows[i][j].ToString(), type));
                        if (j < dt.Columns.Count - 1)
                        {
                            Json.Append(",");
                        }
                    }
                    Json.Append("}");
                    if (i < dt.Rows.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]}");
            return Json.ToString();
        }

        #endregion

        #region private funcation

        /// <summary>
        /// 过滤特殊字符
        /// </summary>
        /// <param name="s">字符串</param>
        /// <returns>json字符串</returns>
        private static string StringCharacter(String s)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < s.Length; i++)
            {
                char c = s.ToCharArray()[i];
                switch (c)
                {
                    case '\"':
                        sb.Append("\\\""); break;
                    case '\\':
                        sb.Append("\\\\"); break;
                    case '/':
                        sb.Append("\\/"); break;
                    case '\b':
                        sb.Append("\\b"); break;
                    case '\f':
                        sb.Append("\\f"); break;
                    case '\n':
                        sb.Append("\\n"); break;
                    case '\r':
                        sb.Append("\\r"); break;
                    case '\t':
                        sb.Append("\\t"); break;
                    default:
                        sb.Append(c); break;
                }
            }
            return sb.ToString();
        }
        /// <summary>
        /// 格式化字符型、日期型、布尔型
        /// </summary>
        /// <param name="str"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private static string StringFormat(string str, Type type)
        {
            if (type == typeof(string))
            {
                str = StringCharacter(str);
                str = "\"" + str + "\"";
            }
            else if (type == typeof(DateTime))
            {
                str = "\"" + str + "\"";
            }
            else if (type == typeof(bool))
            {
                str = str.ToLower();
            }
            else if (type != typeof(string) && string.IsNullOrEmpty(str))
            {
                str = "\"" + str + "\"";
            }
            return str;
        }

        #endregion

        #region 校验Token有效时效

        #endregion

    }
}
